package com.leetcode.partition2;

import java.util.LinkedList;

/**
 * @author `RKC`
 * @date 2021/8/16 10:52
 */
public class LC116填充每个节点的下一个右侧节点指针 {

    public static Node connect(Node root) {
        bfs(root);
        return root;
    }

    public static void main(String[] args) {
        Node root = new Node(1, new Node(2, new Node(4), new Node(5), null),
                new Node(3, new Node(6), new Node(7), null), null);
        root = connect(root);
        System.out.println(root.val);
    }

    private static void bfs(Node root) {
        if (root == null) return;
        LinkedList<Node> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            Node pre = null, cur = null;
            for (int i = 0; i < size; i++) {
                if (i == 0) {
                    pre = queue.pollFirst();
                    cur = pre;
                } else {
                    cur = queue.pollFirst();
                    pre.next = cur;
                    pre = pre.next;
                }
                if (cur.left != null) queue.add(cur.left);
                if (cur.right != null) queue.add(cur.right);
            }
            cur.next = null;
        }
    }

    private static class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }
}
